package handler

import (
	"log"
	"paper-parser/model"
	"regexp"
)

func AnswerNull() {
	nullAnswerNum := 0
	nullStemNum := 0
	orm := model.Orm()
	err := orm.Where("id > ?", 0).Iterate(new(model.Question), func(i int, bean interface{}) error {
		q := bean.(*model.Question)
		//do somthing use i and user
		if q.Answer == "" {
			nullAnswerNum++
			log.Println("No.", q.Id, "null answer")
		}
		if len(q.Stem) < 10 && q.Stem != "如图所示" {
			nullStemNum++
			log.Println("No.", q.Id, "null stem:", q.Stem)
		}
		return nil
	})
	if err != nil {
		log.Println(err)
	}
	log.Println("nullAnswerNum:", nullAnswerNum)
	log.Println("nullStemNum:", nullStemNum)
}

func ChangeQuestion() {
	orm := model.Orm()
	err := orm.Where("id > ?", 0).Iterate(new(model.Question), func(i int, bean interface{}) error {
		q := bean.(*model.Question)
		//do somthing use i and user
		reFirst, err := regexp.Compile(`^(\.|．|。|:|：|、|，|,|]|】|］)`)
		if err != nil {
			log.Println(err)
		}
		q.Stem = reFirst.ReplaceAllString(q.Stem, "")
		for _, v := range q.Selections {
			v = reFirst.ReplaceAllString(v, "")
		}
		q.Explain = reFirst.ReplaceAllString(q.Explain, "")
		_, err = orm.ID(q.Id).Cols("stem", "explain", "selections").Update(q)
		if err != nil {
			log.Println(err)
		}
		return nil
	})
	if err != nil {
		log.Println(err)
	}
}

func FindQuestion() {
	orm := model.Orm()
	err := orm.Where("id > ?", 0).Iterate(new(model.Question), func(i int, bean interface{}) error {
		q := bean.(*model.Question)
		//do somthing use i and user
		reFirst, err := regexp.Compile(`^(\.|．|。|:|：|、|，|,|]|】|］)`)
		if err != nil {
			log.Println(err)
		}
		if reFirst.MatchString(q.Stem) {
			log.Println(q.Stem)
			q.Stem = reFirst.ReplaceAllString(q.Stem, "")
			_, err = orm.ID(q.Id).Cols("stem").Update(q)
		}
		return nil
	})
	if err != nil {
		log.Println(err)
	}
}

func QstStemSpace() {
	orm := model.Orm()
	re, err := regexp.Compile(`[ ]{2,8}`)
	if err != nil {
		log.Fatalln(err)
	}
	times := 0
	err = orm.Where("id > ?", 0).Iterate(new(model.Question), func(i int, bean interface{}) error {
		q := bean.(*model.Question)
		if !re.MatchString(q.Stem) {
			return nil
		}
		times++
		q.Stem = re.ReplaceAllString(q.Stem, "___")
		log.Println(q.Stem)
		ok, err := orm.ID(q.Id).Cols("stem").Update(q)
		if ok == 0 || err != nil {
			log.Println(ok, err)
		}
		return nil
	})
	if err != nil {
		log.Println(err)
	}
	log.Println(times)
}
